package cn.tedu.coolshark.filter;

import cn.tedu.coolshark.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "MyFilter",urlPatterns = {"/insertProduct.html","/admin.html"})
public class MyFilter implements Filter {
    //销毁
    public void destroy() {
    }

    //当接收到请求时会执行此方法
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpSession session = ((HttpServletRequest)req).getSession();
        User user = (User)session.getAttribute("user");
        if(user!=null){
            chain.doFilter(req, resp);//放行
        }else{
            ((HttpServletResponse)resp).sendRedirect("/login.html");
        }
        System.out.println("过滤器被执行了~~~~~~");

    }

    //初始化时调用
    public void init(FilterConfig config) throws ServletException {

    }

}
